import { getClassificationList } from '../../../../api/index'

Component({
  properties: {
    show: {
      type: Boolean,
      value: false
    },
    firstId: {
      type: Number,
      value: ''
    },
    secendId: {
      type: Number,
      value: ''
    },
    threeId: {
      type: Number,
      value: ''
    },
    fourId: {
      type: Number,
      value: ''
    },
    lastId: {
      type: Number,
      value: ''
    }
  },
  data: {
    firstList: [],
    secendList: [],
    threeList: [],
    fourList: []
  },
  methods: {
    beforeOpen () {
      this.getCateList()
      if (this.data.firstId) {
        this.setChildList(this.data.firstList, this.data.firstId, 'secendList', 'secendId', 'threeId')
      }
    },
    async getCateList () {
      try {
        const { ResultSet } = await getClassificationList({})
        this.setData({ firstList: ResultSet.userData.data })
      } catch (err) {
        wx.showToast({ title: err.message || err.ResultSet.errors })
      }
    },
    setChildList (arr, id, key, currentkey, childkey) {
      if (childkey) {
        let currentItem = arr.find(item => item.classificationId === parseInt(id))
        if (currentItem && currentItem.childList && currentItem.childList.length) {
          this.setData({
            [key]: currentItem.childList
          })
        }
      }
      if (childkey === 'threeId' && this.data[currentkey]) {
        this.setChildList(this.data[key], this.data[currentkey], 'threeList', 'threeId', 'fourId')
      }
      if (childkey === 'fourId' && this.data[currentkey]) {
        this.setChildList(this.data[key], this.data[currentkey], 'fourList', 'fourId', '')
      }
    },
    changeCate ({ currentTarget: { dataset: { currentkey, arr, key, child, item } } }) {
      this.setData({
        [currentkey]: item.classificationId,
        lastId: item.classificationId
      })
      if (currentkey === 'firstId') {
        this.setData({
          secendList: [],
          secendId: '',
          threeList: [],
          threeId: '',
          fourList: [],
          fourId: ''
        })
      }
      if (currentkey === 'secendId') {
        this.setData({
          threeList: [],
          threeId: '',
          fourList: [],
          fourId: ''
        })
      }
      if (currentkey === 'threeId') {
        this.setData({
          fourList: [],
          fourId: ''
        })
      }
      this.setChildList(this.data[arr], this.data[currentkey], key, currentkey, child)
    },
    confirm () {
      this.triggerEvent('confirm', { firstId: this.data.firstId, secendId: this.data.secendId, threeId: this.data.threeId, fourId: this.data.fourId, lastId: this.data.lastId })
    },
    cancel () {
      this.triggerEvent('cancel')
    },
  },
})